import { createApp } from "vue";
import { setupStore } from "./store";
import { setupAssets } from "./plugins";
// import './assets/font/iconfont.css'
import "@/assets/icon/iconfont.css";

import { Input, Picker, Textarea, Button, Tabs, TabPane, Popup, DatePicker, Form, FormItem, Checkbox, CheckboxGroup, Calendar, Radio, RadioGroup } from "@nutui/nutui-taro";
import Taro from "@tarojs/taro";
// import { getDemographicInfo, getFamilyByIdcard } from "./pages/index/tooler";
import { localStg, PageStats } from "./utils";
import { useDemographicInfoStore } from '@/store/modules/demographic'
import { useAuthStore } from '@/store/modules/auth'
import { queryByOpenId } from '@/service/api/nurse_user'



// post('/dictionary/region', {
//   fatherId: 7459
// }).then(res => {
//   console.log("res", res);
// });


// 设置路由监听
function setupRouteListener() {
  try {
    // 保存原始的导航方法
    const originalNavigateTo = Taro.navigateTo;
    const originalRedirectTo = Taro.redirectTo;
    const originalSwitchTab = Taro.switchTab;
    const originalReLaunch = Taro.reLaunch;
    const originalNavigateBack = Taro.navigateBack;

    // 重写 navigateTo 方法
    Taro.navigateTo = function(options: any) {
      console.log('navigateTo:', options.url);
      PageStats.recordPageVisit(options.url);
      return originalNavigateTo.call(this, options);
    };

    // 重写 redirectTo 方法
    Taro.redirectTo = function(options: any) {
      console.log('redirectTo:', options.url);
      PageStats.recordPageVisit(options.url);
      return originalRedirectTo.call(this, options);
    };

    // 重写 switchTab 方法
    Taro.switchTab = function(options: any) {
      console.log('switchTab:', options.url);
      PageStats.recordPageVisit(options.url);
      return originalSwitchTab.call(this, options);
    };

    // 重写 reLaunch 方法
    Taro.reLaunch = function(options: any) {
      console.log('reLaunch:', options.url);
      PageStats.recordPageVisit(options.url);
      return originalReLaunch.call(this, options);
    };

    // 重写 navigateBack 方法
    Taro.navigateBack = function(options: any) {
      console.log('navigateBack');
      // 对于返回操作，我们需要获取当前页面栈中的前一个页面
      setTimeout(() => {
        const currentPages = Taro.getCurrentPages();
        if (currentPages.length > 0) {
          const currentPage = currentPages[currentPages.length - 1];
          PageStats.recordPageVisit(`/${currentPage.route}`);
        }
      }, 100); // 延迟执行，确保页面已经切换
      return originalNavigateBack.call(this, options);
    };

    console.log('路由监听已设置 - 通过重写导航方法');
  } catch (error) {
    console.error('设置路由监听失败:', error);
  }
}

const App = createApp({
  onShow() {
    // 应用显示时的其他逻辑
  },
  async onLaunch() {
    // console.error("onLaunch");
    // 从地址栏url search 中获取参数idcard
    const urlParams = new URLSearchParams(window.location.search);
    const openid = urlParams.get("openid");
    const idcard = urlParams.get("idcard");
    const phone = urlParams.get("phone");
    const platform = urlParams.get("platform");
    console.log(`idcard: ${idcard}, phone: ${phone}, platform: ${platform}`);
    if (!idcard) {
      Taro.showToast({
        title: "请传入身份证号码",
        icon: "none",
      });
      return;
    }
    if (!phone) {
      Taro.showToast({
        title: "请传入手机号码",
        icon: "none",
      });
      return;
    }
    localStg.set("idcard", idcard);
    localStg.set("phone", phone);
    localStg.set("platform", platform);
    // localStg.set("openid", openid);
    // localStg.set("token", token);
    // console.log("demographicInfo -->2");
    const demographicStore = useDemographicInfoStore();
    const authStore = useAuthStore();
    
    // 保存当前电话号码到 authStore
    if (phone) {
      authStore.setCurrentPhone(phone);
      console.log("当前电话号码已保存到 authStore:", phone);
    }
    // console.log("demographicInfo -->3");
    demographicStore.setPlatform(platform || '')
    await demographicStore.getDemographicInfoByPhone(phone)
    // console.log("demographicInfo -->4");
    console.log("demographicStore.currentInfo", demographicStore.currentInfo);

    // 初始化页面统计
    console.log("初始化页面访问统计");
    const pageStats = PageStats.getPageStats();
    console.log("当前页面访问统计:", pageStats);

    // 获取用户信息并存储到store和本地缓存
    if (openid) {
      try {
        console.log("开始获取用户信息，openid:", openid);
        const userInfoResponse = await queryByOpenId({ openid });
        
        if (userInfoResponse?.success) {
          const userInfo = userInfoResponse.success;
          console.log("获取到用户信息:", userInfo);
          
          // 存储到auth store
          authStore.setNurseUser(userInfo);
          
          // 存储到本地缓存
          localStg.set("nurseUser", userInfo);
          localStg.set("openid", openid);
          
          console.log("用户信息已存储到store和本地缓存");
        } else {
          console.warn("获取用户信息失败:", userInfoResponse);
        }
      } catch (error) {
        console.error("获取用户信息时发生错误:", error);
        Taro.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    }

    if(!demographicStore.currentInfo){
      demographicStore.setInfoByOpenId(openid || '', phone)
      // getNurseUserByOpenId(openid || '', phone).then((res: any) => {
      //   console.log("res", res);
      //   if(res){
      //     demographicStore.setCurrentInfo({
      //       ...res
      //     })
      //   }
      // })
    }
    
    // 设置路由监听，在每次页面切换时记录访问
    setupRouteListener();
    // getFamilyByIdcard(idcard)
    // getNurseUserByOpenId(openid)
  },
  /** 入口组件不需要实现 render 方法，即使实现了也会被 taro 所覆盖 */
});

// 引入静态资源和样式
setupAssets();
console.log("app init")
// 页面访问统计功能已集成，自动记录每个页面的打开次数到 localStorage

// 注册 Pinia 状态管理
// App.use(pinia);
App.use(Input);
App.use(Picker);
App.use(Textarea);
App.use(Button);
App.use(Tabs);
App.use(TabPane);
App.use(Popup);
App.use(DatePicker);
App.use(Form);
App.use(FormItem);
App.use(Calendar);
App.use(Radio);
App.use(RadioGroup);
App.use(Checkbox);
App.use(CheckboxGroup);

setupStore(App);

export default App;
